package cn.tedu;

import java.sql.*;
import java.util.Scanner;

public class Demo10 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println( "输入账号");
         String username = scan.nextLine();
        System.out.println("请输入密码");
         String password = scan.nextLine();
        try (
                Connection conn = DBUtils .getConn();
                ){
            /*Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery
                    ("select count(*) from user where username='"+username+"' and password='"+password+"'");*/
            //通过PreparedStatement解决SQL注入问题
            String sql = "select count(*) from user where username=? and password=?";
            //编译SQL语句的时间点从之前执行时,提前到了创建对象时, 好处是此时编译用户输入的内容
            //还不在SQL语句里面,只是将原有SQL语句进行编译, 此时可以将原有SQL语句的逻辑部分锁死
            PreparedStatement ps = conn.prepareStatement(sql);
            //把?替换成变量 1和2代表的是?的位置  此时替换时只能以值的形式添加到原有SQL语句中,因为
            //逻辑部分已经编译好 已经锁死,这样用户输入的内容则不会影响原有SQL语句的逻辑。
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
             rs.next();
             int count = rs.getInt(1);
             if(count>0){
                 System.out.println("登录成功");
             }else {
                 System.out.println("登录失败");
             }
           /* ResultSet rs = s.executeQuery
                    ("select *from user where username='"+username+"' and password='"+password+"'");
            if(rs.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }
*/
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
